package com.edu.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.entity.Conditions;
import com.edu.entity.Goods;
import com.edu.entity.GoodsToWeb;
import com.edu.entity.Tool;
import com.edu.entity.User;
import com.edu.service.impl.UserServerImpl;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;

/**
 * Servlet implementation class addUser
 */
@MultipartConfig(
	    fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
	    maxFileSize = 1024 * 1024 * 10,      // 10 MB
	    maxRequestSize = 1024 * 1024 * 15    // 15 MB
	)
@WebServlet("/addUser")
public class addUser extends HttpServlet {
	private static final String SAVE_DIR = "C:\\poj-java\\goodimg";
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		UserServerImpl usi = new UserServerImpl();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
	    PrintWriter out = response.getWriter();
		Tool t1 = new Tool();
		User user = new User();
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		user.setSex(t1.sexToInt(request.getParameter("gen")));
		String dateStr = request.getParameter("date");
		Date utilDate = null;
		    try {
		        // 转换为LocalDate
		        LocalDate birthday = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		        
		        // 如果需要java.util.Date
		        utilDate = (Date) Date.from(birthday.atStartOfDay(ZoneId.systemDefault()).toInstant());
		        
		    } catch (DateTimeParseException e) {
		        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "日期格式不正确");
		    }
		user.setBrithday(utilDate);
		File saveDir = new File(SAVE_DIR);
		Part filePart = request.getPart("headImg");
		String visPath = "";
		if(filePart.getSize() > 0 && filePart.getSubmittedFileName() != null) {
			  String fileName = getUniqueFileName(filePart.getSubmittedFileName());
			  String filePath = SAVE_DIR + File.separator + fileName;
		      try (InputStream fileContent = filePart.getInputStream()) {
		          Files.copy(fileContent, Paths.get(filePath));
		      }
		      visPath = "/poj-java/goodimg/" + fileName;
		}else {
			System.out.println("未获取头像，使用默认");
			visPath = "/poj-java/goodimg/headimg_def.jpg";
		}
        user.setHeadimg(visPath);
        int returnNum = usi.addUser(user);
        System.out.println(returnNum);
		System.out.println(user.toString());
		ObjectMapper om = new ObjectMapper();
		String signInfo = t1.errorCodeToString(returnNum);
		System.out.println(signInfo);
		PrintWriter pw = response.getWriter();
		pw.print(signInfo);
		pw.flush();
		return;
	}

	private String getUniqueFileName(String submittedFileName) {
		// TODO Auto-generated method stub
		UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();
        String newName = uuidString+"_"+submittedFileName;
        System.out.println("分配id:" + newName);
		return newName;
	}
}
